package com.zyc.ir;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.ConsumerIrManager;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "ConsumerIrTest";
    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor mEditor;

    //红外遥控ConsumerIrManager
    private ConsumerIrManager mCIR;

    private static final int IR_H = 1685;
    private static final int IR_L = 565;
    private static final int[] IR_DATA_LH = {IR_L, IR_H};
    List<Integer> data = new ArrayList<Integer>();


    List<Map<String, Object>> ListDate = new ArrayList<>();
    List<ArrayList<Integer>> IRDate = new ArrayList<>();
    List<Button> button = new ArrayList<>();
    List<LinearLayout> linear = new ArrayList<>();
    LinearLayout root;

    @SuppressLint("InlinedApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 获取系统的红外遥控服务
        mCIR = (ConsumerIrManager) getSystemService(Context.CONSUMER_IR_SERVICE);

        Log.e("log", "ir:" + mCIR.hasIrEmitter());
        if (!mCIR.hasIrEmitter()) {
            new AlertDialog.Builder(this)
                    .setTitle("未找到红外设备!")
                    .setMessage("未检测到您手机上的红外设备,此软件可能无法正常使用,退出?")
                    .setPositiveButton("退出", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .show();
        }


        findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addbutton();
            }
        });
        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delbutton();
            }
        });
        root = (LinearLayout) findViewById(R.id.ll_root);
        mSharedPreferences = getSharedPreferences("IR_Setting", 0);
        int num = mSharedPreferences.getInt("Num", 0);
        for (int i = 0; i < num; i++) {
            addbutton();
        }

        for (int i = 0; i < num; i++) {
            mSharedPreferences.getInt("Num", 0);

            button.get(i).setText(mSharedPreferences.getString("title" + i, "按钮" + i));
            IRDate.add(i, str2list(mSharedPreferences.getString("dat" + i, "00 00 00 00")));


        }

    }


    View.OnClickListener mSendClickListener = new View.OnClickListener() {
        @TargetApi(Build.VERSION_CODES.KITKAT)
        public void onClick(View v) {
            if (!mCIR.hasIrEmitter()) {
                Log.e(TAG, "未找到红外发射器！");
                Toast.makeText(MainActivity.this, "未找到红外发射器！", Toast.LENGTH_SHORT).show();
                return;
            }
            List<Integer> by = new ArrayList<>();
            Log.v(TAG, "按键按下:" + v.getId());
            mCIR.transmit(38000, list2int(hex2list(IRDate.get(v.getId()))));
        }
    };

    View.OnLongClickListener mSendLongClickListener = new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            popupwindow(v.getId());
            return false;
        }
    };

    private void addbutton() {
        int btNum = button.size();
        if (button.size() % 3 == 0) {
            linear.add(new LinearLayout(this));
            root.addView(linear.get(linear.size() - 1));
        }

        Button btn = new Button(this);

        btn.setId(button.size());
        btn.setEms(8);
        btn.setLayoutParams(new LinearLayout.LayoutParams(0, -1, 1));
        btn.setText("发送" + btn.getId());
        btn.setOnClickListener(mSendClickListener);
        btn.setOnLongClickListener(mSendLongClickListener);

        button.add(btn);
        linear.get(linear.size() - 1).addView(btn);


        IRDate.add(new ArrayList<Integer>(Arrays.asList(0, 0, 0, 0)));

    }

    private void delbutton() {

        try {
            linear.get(linear.size() - 1).removeView(button.get(button.size() - 1));

            IRDate.remove(IRDate.size() - 1);
            button.remove(button.size() - 1);
            if (button.size() % 3 == 0) {
                root.removeView(linear.get(linear.size() - 1));
                linear.remove(linear.size() - 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private ArrayList<Integer> str2list(String str) {
        if (str == null || str.length() < 0) return null;
        ArrayList<Integer> val = new ArrayList<>();
        String[] st = str.toUpperCase().trim().split(" ");

        for (String s : st) {
            val.add(str2hex(s));
        }

        String strval = "";
        for (int i = 0; i < val.size(); i++)
            strval = strval + String.format(" %02x", val.get(i));
        Log.d(TAG, "val:" + strval);
        if (val.size() == 0) {
            val.add(0);
            val.add(0);
            val.add(0);
            val.add(0);
        }

        return val;
    }

    private int str2hex(String str1) {
        String str = str1.toUpperCase();
        if (str.length() == 0) return 0;
        else if (str.length() == 1) {
            char temp = str.charAt(0);
            if (temp >= 0x30 && temp <= 0x39)
                return temp - 0x30;
            else if (temp >= 0x41 && temp <= 0x46) {//已经转为大写
                return temp - 55;
            }
        } else {
            int a = 0;
            char temp = str.charAt(0);
            if (temp >= 0x30 && temp <= 0x39)
                a = temp - 0x30;
            else if (temp >= 0x41 && temp <= 0x46) {//已经转为大写
                a = temp - 55;
            }
            a = a * 16;
            temp = str.charAt(1);
            if (temp >= 0x30 && temp <= 0x39)
                a += temp - 0x30;
            else if (temp >= 0x41 && temp <= 0x46) {//已经转为大写
                a += temp - 55;
            }
            return a;
        }
        return 0;
    }

    private List<Integer> hex2list(List<Integer> b) {
        List<Integer> list = new ArrayList<>();
        list.add(9000);
        list.add(4000);
        list.add(560);

        for (int j = 0; j < b.size(); j++) {
            int temp = b.get(j);
            for (int i = 0; i < 8; i++) {
                if ((temp & 0x80) == 0x80) list.add(IR_H);
                else list.add(IR_L);
                list.add(560);
                temp = (temp << 1);
            }

//            list.add(41525);
//            list.add(9000);
//            list.add(2215);
//            list.add(560);
        }
        return list;
    }

    private int[] list2int(List<Integer> intList) {
        int[] a = new int[intList.size()];
        for (int i = 0; i < intList.size(); i++) a[i] = intList.get(i);
        return a;
    }


    //region 弹窗
    private void popupwindow(final int id) {

        View popupView = getLayoutInflater().inflate(R.layout.popupwindow_button_setting, null);
        final PopupWindow window = new PopupWindow(popupView, -2, -2, true);//match_parent,match_parent
        final EditText et_name = (EditText) popupView.findViewById(R.id.et_name);
        final EditText et_ir = (EditText) popupView.findViewById(R.id.et_ir);
        final Button bt = (Button) popupView.findViewById(R.id.bt_save);

        et_name.setText(button.get(id).getText());
        String strval = "";
        for (int i = 0; i < IRDate.get(id).size(); i++)
            strval = strval + String.format("%02x ", IRDate.get(id).get(i));
        et_ir.setText(strval.trim());
        window.setBackgroundDrawable(new BitmapDrawable());
        window.setOutsideTouchable(true);

        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                button.get(id).setText(et_name.getText());
                IRDate.add(id, str2list(et_ir.getText().toString()));
                SaveIR(id, et_name.getText().toString(), et_ir.getText().toString());
                window.dismiss();
            }
        });

        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
        window.update();
        window.showAtLocation(popupView, Gravity.CENTER, 0, 0);
    }
    //endregion


    private void SaveIR(int id, String title, String str) {
        //region 获取蓝牙设备地址
        mSharedPreferences = getSharedPreferences("IR_Setting", 0);
        mEditor = getSharedPreferences("IR_Setting", 0).edit();
        int num = mSharedPreferences.getInt("Num", 0);
        if (num < id + 1) {
            mEditor.putInt("Num", id + 1);
        }
        mEditor.putString("title" + id, title);
        mEditor.putString("dat" + id, str);
        mEditor.commit();
    }

}
